package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.blankj.utilcode.util.SizeUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.listener.OnForumChooseListener;
import com.chexiehui.jc.mvp.mine.ChooseCarForumCovenant;
import com.chexiehui.jc.mvp.mine.ChooseCarForumPresenter;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * 选论坛
 */
public class ChooseCarForumFragment extends BaseMvpFragment<ChooseCarForumPresenter> implements ChooseCarForumCovenant.View {


    @BindView(R.id.tv_series_name)
    TextView tvSeriesName;
    @BindView(R.id.tv_series_price)
    TextView tvSeriesPrice;
    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private DelegateAdapter listAdapter;
    private BasePage<ForumInfo> page;
    private CommVLayoutAdapter<ForumInfo> forumListAdapter;
    //    private BrandInfo brandInfo;
    private CarSeriesInfo carSeriesInfo;
    private OnForumChooseListener onForumChooseListener;

    public static ChooseCarForumFragment getInstance(CarSeriesInfo carSeriesInfo) {
        ChooseCarForumFragment fragment = new ChooseCarForumFragment();
        Bundle bundle = new Bundle();
//        bundle.putSerializable("brand", brandInfo);
        bundle.putSerializable("entity", carSeriesInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
//            brandInfo = (BrandInfo) bundle.get("brand");
            carSeriesInfo = (CarSeriesInfo) bundle.get("entity");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_choose_car_forum;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableOverScrollDrag(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (carSeriesInfo == null) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (carSeriesInfo == null) {
                    refreshLayout.finishLoadMore(false);
                    return;
                }
                if (page != null && page.getTotalRecordCount() > forumListAdapter.getData().size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        tvSeriesName.setText(carSeriesInfo.getName());
        tvSeriesPrice.setText(carSeriesInfo.getPriceMaxMinStr());
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mActivity);
        mRecycler.setLayoutManager(virtualLayoutManager);
        ((SimpleItemAnimator) mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecycler.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        mRecycler.setAdapter(listAdapter);
        int dp_10 = SizeUtils.dp2px(10);
        LinearLayoutHelper helper = new LinearLayoutHelper(SizeUtils.dp2px(1));
        helper.setMargin(0, dp_10, 0, dp_10);
        helper.setBgColor(ContextCompat.getColor(mActivity, R.color.colorTransparent));
        forumListAdapter = new CommVLayoutAdapter<ForumInfo>(mActivity, new ArrayList<>(),
                R.layout.item_choose_forum, helper) {
            @Override
            public void convert(ViewHolder holder, int position, ForumInfo item) {
                holder.setText(R.id.tv_item_name, item.getName());
            }
        };
        forumListAdapter.setItemClickListener((view, position, item) -> {
            if (onForumChooseListener != null) {
                onForumChooseListener.onForumChoose(item);
            }
        });
        listAdapter.addAdapter(forumListAdapter);
        if (carSeriesInfo == null) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("没有找到任何数据");
            return;
        }
        mvpPresenter.getList(1);
    }

    @Override
    protected ChooseCarForumPresenter createPresenter() {
        return new ChooseCarForumPresenter(this);
    }

    public void setOnChooseListener(OnForumChooseListener listener) {
        this.onForumChooseListener = listener;
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<ForumInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            forumListAdapter.getData().clear();
            forumListAdapter.getData().addAll(page.getItems());
            forumListAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            forumListAdapter.getData().addAll(page.getItems());
            forumListAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= forumListAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            forumListAdapter.getData().clear();
            forumListAdapter.getData().addAll(page.getItems());
            forumListAdapter.notifyDataSetChanged();
        }
        if (loadingLayout.getStatus() == LoadingLayout.Loading) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (forumListAdapter.getData().size() > 0) {
                    forumListAdapter.getData().clear();
                    forumListAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (forumListAdapter.getData().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public String getSeriesId() {
        return carSeriesInfo.getId();
    }

}
